package com.wutong.teacher_server.excel.utils;

import com.wutong.teacher_server.excel.annotation.ExcelAttribute;
import com.wutong.teacher_server.utils.DateUtil;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.*;


/**
 * Create By Administrator on 2020/11/4.
 */
/*
 * ExcelUtil工具类实现功能:
 * 导出时传入list<T>,即可实现导出为一个excel,其中每个对象Ｔ为Excel中的一条记录.
 * 导入时读取excel,得到的结果是一个list<T>.T是自己定义的对象.
 * 需要导出的实体对象只需简单配置注解就能实现灵活导出,通过注解您可以方便实现下面功能:
 * 1.实体属性配置了注解就能导出到excel中,每个属性都对应一列.
 * 2.列名称可以通过注解配置.
 * 3.导出到哪一列可以通过注解配置.
 * 4.鼠标移动到该列时提示信息可以通过注解配置.
 * 5.用注解设置只能下拉选择不能随意填写功能.
 * 6.用注解设置是否只导出标题而不导出内容,这在导出内容作为模板以供用户填写时比较实用.
 */
public class ExcelUtil<T> {

    Logger logger = LoggerFactory.getLogger(ExcelUtil.class);
    Class<T> clazz;

    public ExcelUtil(Class<T> clazz) {
        this.clazz = clazz;
    }

    /**
     * 读取第1个sheet
     *
     * @param input
     * @return
     */
    public List<T> importExcel(InputStream input) {
        return importExcel("", input);
    }

    public List<T> importExcel(String sheetName, InputStream input) {
        int maxCol = 0;
        List<T> list = new ArrayList<>();
        try {
            HSSFWorkbook workbook = new HSSFWorkbook(input);
            HSSFSheet sheet = workbook.getSheet(sheetName);
            if (!sheetName.trim().equals("")) {
                sheet = workbook.getSheet(sheetName);// 如果指定sheet名,则取指定sheet中的内容.  
            }
            if (sheet == null) {
                sheet = workbook.getSheetAt(0); // 如果传入的sheet名不存在则默认指向第1个sheet.  
            }
            int rows = sheet.getPhysicalNumberOfRows();

            if (rows > 0) {// 有数据时才处理
                List<Field> allFields = getMappedFiled(clazz, null);

                Map<Integer, Field> fieldsMap = new HashMap<>();// 定义一个map用于存放列的序号和field.
                for (Field field : allFields) {
                    // 将有注解的field存放到map中.  
                    if (field.isAnnotationPresent(ExcelAttribute.class)) {
                        ExcelAttribute attr = field.getAnnotation(ExcelAttribute.class);
                        int col = getExcelCol(attr.column());// 获得列号  
                        maxCol = Math.max(col + 1, maxCol);
                        field.setAccessible(true);// 设置类的私有字段属性可访问.  
                        fieldsMap.put(col, field);
                    }
                }
                for (int i = 1; i < rows; i++) {// 从第2行开始取数据,默认第一行是表头.  
                    HSSFRow row = sheet.getRow(i);
                    int cellNum = maxCol;
                    T entity = null;
                    for (int j = 0; j < cellNum; j++) {
                        HSSFCell cell = row.getCell(j);
                        if (cell == null) {
                            continue;
                        }
                        cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                        int cellType = cell.getCellType();

                        String c = "";
                        if (cellType == HSSFCell.CELL_TYPE_NUMERIC) {
                            c = String.valueOf(cell.getNumericCellValue());
                        } else if (cellType == HSSFCell.CELL_TYPE_BOOLEAN) {
                            c = String.valueOf(cell.getBooleanCellValue());
                        } else {
                            c = cell.getStringCellValue();
                        }
                        if (c == null || c.equals("")) {
                            continue;
                        }
                        entity = (entity == null ? clazz.newInstance() : entity);// 如果不存在实例则新建.
                        Field field = fieldsMap.get(j);// 从map中得到对应列的field.  
                        if (field == null) {
                            continue;
                        }
                        // 取得类型,并根据对象类型设置值.  
                        Class<?> fieldType = field.getType();
                        if (String.class == fieldType) {
                            field.set(entity, String.valueOf(c));
                        } else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType)) {
                            field.set(entity, Integer.parseInt(c));
                        } else if ((Long.TYPE == fieldType) || (Long.class == fieldType)) {
                            field.set(entity, Long.valueOf(c));
                        } else if ((Float.TYPE == fieldType) || (Float.class == fieldType)) {
                            field.set(entity, Float.valueOf(c));
                        } else if ((Short.TYPE == fieldType) || (Short.class == fieldType)) {
                            field.set(entity, Short.valueOf(c));
                        } else if ((Double.TYPE == fieldType) || (Double.class == fieldType)) {
                            field.set(entity, Double.valueOf(c));
                        } else if (Character.TYPE == fieldType && (c != null) && (c.length() > 0)) {
                            field.set(entity, Character.valueOf(c.charAt(0)));
                        }

                    }
                    if (entity != null) {
                        list.add(entity);
                    }
                }
            }

        } catch (Exception e) {
            logger.info(e.toString());
        }
        return list;
    }

    /**
     * 对list数据源将其里面的数据导入到excel表单
     *
     * @param
     * @param output java输出流
     */
    public boolean exportExcel(List<T> list, String sheetName, OutputStream output) {

        HSSFWorkbook workbook = new HSSFWorkbook();// 产生工作薄对象
        workbook.createSheet();// 产生工作表对象
        return exportExcel(list, output, workbook, sheetName);
    }

    /**
     * 对list数据源将其里面的数据导入到excel表单
     *
     * @param sheetName 工作表的名称
     * @param output    java输出流
     */
    public boolean exportExcel(List<T> list, OutputStream output, HSSFWorkbook workbook, String sheetName) {
        HSSFCellStyle style = workbook.createCellStyle();
        style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
        style.setFillBackgroundColor(HSSFColor.GREY_40_PERCENT.index);

        List<Field> fields = getMappedFiled(clazz, null);
        HSSFSheet sheet = null;
        HSSFRow row = null;
        HSSFCell cell = null;// 产生单元格

        if (!sheetName.trim().equals("")) {
            sheet = workbook.getSheet(sheetName);// 如果指定sheet名,则取指定sheet中的内容.  
        }
        if (sheet == null) {
            workbook.setSheetName(0, sheetName);
            sheet = workbook.getSheetAt(0); // 如果传入的sheet名不存在则默认指向第1个sheet.  
        }

        row = sheet.createRow(0);// 产生一行

        creatTitle(fields, sheet, row, cell, style, workbook);

        int startNo = 0;
        int endNo = list.size();
        // 写入各条记录,每条记录对应excel表中的一行
        int index = 0;//记录额外创建的sheet数量

        Integer sheetMaxSize = 60000;  //单页sheet最大数据量
        for (int i = startNo; i < endNo; i++) {
            if ((i + index + 1) % sheetMaxSize == 0) {
                sheet = workbook.createSheet(sheetName + index);
                row = sheet.createRow(0);// 产生一行
                creatTitle(fields, sheet, row, cell, style, workbook);
                index++;
            }
            //					row = sheet.createRow(i + 1 - startNo);
            if (index == 0) {
                row = sheet.createRow((i + 1) - startNo);
            } else {
                row = sheet.createRow((i + 1) - startNo - (index * sheetMaxSize) + index);
            }

            T vo = list.get(i); // 得到导出对象.
            writeExcel(fields, row, cell, vo);
        }
        try {
            output.flush();
            workbook.write(output);
            output.close();
            return true;
        } catch (IOException e) {
            return false;
        }
    }


    public void creatTitle(List<Field> fields, HSSFSheet sheet, HSSFRow row, HSSFCell cell, HSSFCellStyle style, HSSFWorkbook workbook) {
        // 写入各个字段的列头名称
        for (int i = 0; i < fields.size(); i++) {
            Field field = fields.get(i);
            ExcelAttribute attr = field.getAnnotation(ExcelAttribute.class);
            int col = getExcelCol(attr.column());// 获得列号
            sheet.setColumnWidth(col, attr.width() * 256);
            cell = row.createCell(col);// 创建列
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);// 设置列中写入内容为String类型

            cell.setCellValue(attr.name());// 写入列名
            // 如果设置了提示信息则鼠标放上去提示.
            if (!attr.prompt().trim().equals("")) {
                setHSSFPrompt(sheet, "", attr.prompt(), 1, 100, col, col);// 这里默认设了2-101列提示.
            }
            // 如果设置了combo属性则本列只能选择不能输入
            if (attr.combo().length > 0) {
                setHSSFValidation(sheet, attr.combo(), 1, 100, col, col);// 这里默认设了2-101列只能选择不能输入.
            }
            style = workbook.createCellStyle();
            style.setFillForegroundColor(IndexedColors.BRIGHT_GREEN.getIndex());
            style.setFillPattern(CellStyle.SOLID_FOREGROUND);
            HSSFFont font = workbook.createFont();
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);         //字体增粗
            style.setFont(font);
            style.setFont(font);
            style.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
            style.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
            style.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
            style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
            cell.setCellStyle(style);

        }
    }


    public void writeExcel(List<Field> fields, HSSFRow row, HSSFCell cell, T vo) {
        for (int j = 0; j < fields.size(); j++) {
            Field field = fields.get(j);// 获得field.
            field.setAccessible(true);// 设置实体类私有属性可访问
            // 取得类型,并根据对象类型设置值.
            Class<?> fieldType = field.getType();
            ExcelAttribute attr = field.getAnnotation(ExcelAttribute.class);
            try {
                // 根据ExcelAttribute中设置情况决定是否导出,有些情况需要保持为空,希望用户填写这一列.
                if (attr.isExport()) {
                    cell = row.createCell(getExcelCol(attr.column()));// 创建cell
                    cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                    if (Date.class == fieldType) {
                        cell.setCellValue(field.get(vo) == null ? "" : DateUtil.dateToStr((Date) field.get(vo), "GMT"));// 如果数据存在就填入,不存在填入空格.
                    } else {
                        if ("gateway".equals(field.getName())) {
                            String exportValue = "";
                            if ("1".equals(String.valueOf(field.get(vo)))) {
                                exportValue = "出口";
                            } else if ("2".equals(String.valueOf(field.get(vo)))) {
                                exportValue = "入口";
                            } else if ("3".equals(String.valueOf(field.get(vo)))) {
                                exportValue = "不分出入口";
                            }
                            cell.setCellValue(exportValue);
                        } else {
                            cell.setCellValue(field.get(vo) == null ? "" : String.valueOf(field.get(vo)));// 如果数据存在就填入,不存在填入空格.
                        }
                    }
                }
            } catch (Exception e) {
                logger.info(e.toString());
            }
        }
    }


    /**
     * 将EXCEL中A,B,C,D,E列映射成0,1,2,3
     *
     * @param col
     */
    public static int getExcelCol(String col) {
        col = col.toUpperCase();
        // 从-1开始计算,字母重1开始运算。这种总数下来算数正好相同。  
        int count = -1;
        char[] cs = col.toCharArray();
        for (int i = 0; i < cs.length; i++) {
            int temp = cs.length - 1 - i;
            count += (cs[i] - 64) * Math.pow(26, temp);
        }
        return count;
    }

    /**
     * 设置单元格上提示
     *
     * @param sheet         要设置的sheet.
     * @param promptTitle   标题
     * @param promptContent 内容
     * @param firstRow      开始行
     * @param endRow        结束行
     * @param firstCol      开始列
     * @param endCol        结束列
     * @return 设置好的sheet.
     */
    public static HSSFSheet setHSSFPrompt(HSSFSheet sheet, String promptTitle, String promptContent, int firstRow, int endRow, int firstCol, int endCol) {
        // 构造constraint对象  
        DVConstraint constraint = DVConstraint.createCustomFormulaConstraint("DD1");
        // 四个参数分别是：起始行、终止行、起始列、终止列  
        CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
        // 数据有效性对象  
        HSSFDataValidation dataValidationList = new HSSFDataValidation(regions, constraint);
        dataValidationList.createPromptBox(promptTitle, promptContent);
        sheet.addValidationData(dataValidationList);
        return sheet;
    }

    /**
     * 设置某些列的值只能输入预制的数据,显示下拉框.
     *
     * @param sheet    要设置的sheet.
     * @param textlist 下拉框显示的内容
     * @param firstRow 开始行
     * @param endRow   结束行
     * @param firstCol 开始列
     * @param endCol   结束列
     * @return 设置好的sheet.
     */
    public static HSSFSheet setHSSFValidation(HSSFSheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol) {
        // 加载下拉列表内容  
        DVConstraint constraint = DVConstraint.createExplicitListConstraint(textlist);
        // 设置数据有效性加载在哪个单元格上,四个参数分别是：起始行、终止行、起始列、终止列  
        CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
        // 数据有效性对象  
        HSSFDataValidation dataValidationList = new HSSFDataValidation(regions, constraint);
        sheet.addValidationData(dataValidationList);
        return sheet;
    }

    /**
     * 得到实体类所有通过注解映射了数据表的字段
     *
     * @param
     * @return
     */
    @SuppressWarnings("rawtypes")
    private List<Field> getMappedFiled(Class clazz, List<Field> fields) {
        if (fields == null) {
            fields = new ArrayList<>();
        }
        Field[] allFields = clazz.getDeclaredFields();// 得到所有定义字段  
        // 得到所有field并存放到一个list中.  
        for (Field field : allFields) {
            if (field.isAnnotationPresent(ExcelAttribute.class)) {
                fields.add(field);
            }
        }
        if (clazz.getSuperclass() != null && !clazz.getSuperclass().equals(Object.class)) {
            getMappedFiled(clazz.getSuperclass(), fields);
        }
        return fields;
    }
}